﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace SPDbFileExtractor.Framework.Entities
{
    /// <summary>
    /// File
    /// </summary>
    public class FileContent
    {
        /// <summary>
        /// Gets or sets the file id.
        /// </summary>
        /// <value>
        /// The file id.
        /// </value>
        public Guid FileId { get; set; }

        /// <summary>
        /// Gets or sets the internal version.
        /// </summary>
        /// <value>
        /// The internal version.
        /// </value>
        public int InternalVersion { get; set; }

        /// <summary>
        /// Gets or sets the content.
        /// </summary>
        /// <value>
        /// The content.
        /// </value>
        public byte[] Content { get; set; }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0} v{1}", FileId, InternalVersion);
        }

        /// <summary>
        /// Gets the collection from table.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <returns></returns>
        public static FileContent GetSingleItemFromTable(DataTable table)
        {
            if (table == null || table.Rows.Count == 0)
            {
                return null;
            }

            var result = new List<FileContent>();

            foreach (DataRow row in table.Rows)
            {
                FileContent content = new FileContent();
                content.Content = (byte[]) row["Content"];
                content.FileId = new Guid(row["FileId"].ToString());
                content.InternalVersion = (int)row["InternalVersion"];

                result.Add(content);
            }

            return result.First();
        }
    }
}
